function ProductAdd_Code(id) {
	var buffer = new StringBuffer();
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">产品编号</div><div class="require">*</div></div><div class="ctext"><input id="txt_num" type="text" placeholder="填写产品编号" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">产品名称</div><div class="require">*</div></div><div class="ctext"><input id="txt_name" type="text" placeholder="填写产品名称" value=""/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">产品类别</div><div class="require">*</div></div><div class="ctext"><select id="txt_categoryid"></select></div><div id="position" class="carrow"><img src="img/arrow.png"/></div></div>');
	
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">成本价</div><div class="require">*</div></div><div class="ctext"><input id="txt_costprice" type="tel" placeholder="填写成本价" value="" onfocus="ScrollTop()"/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">售价</div><div class="require">*</div></div><div class="ctext"><input id="txt_price" type="tel" placeholder="填写售价" value="" onfocus="ScrollTop()"/></div><div class="carrow"></div></div>');
	buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">产品单位</div><div class="require">*</div></div><div class="ctext"><select id="txt_unit"></select></div><div class="carrow"><img src="img/arrow.png"/></div></div>');
	
	buffer.append('<div id="selfcontent" val="'+id+'">');
	buffer.append('</div>');
	buffer.append('<div id="addphoto" class="crmsheet border-bottom" style="height:90px; padding-top:20px;"><div class="ctitle"><div class="cname" style="padding-top:10px;">产品图片</div></div><div class="ctext" style="width:50%; padding-top:13px;"><img src="img/add2.png"/></div><div id="photopanel" style="width:20%; float:left; text-align:right;"></div></div>');
	buffer.append('<div class="crmsheet border-bottom" style="height:120px;"><div class="ctitle"><div class="cname">备注</div></div><textarea id="txt_bak" placeholder="填写备注" onfocus="ScrollTop()"></textarea></div>');
	return buffer.toString();
};

var map;
var wsub;
var count=0;
var old_img="";
function Init_ProductAdd(){
	var contactid=$("#selfcontent").attr("val");
	var customer;
	if(contactid!=0)
	{
		var data = {};
		data.act = "One_Product";
		data.id=contactid;
		data.source=source;
		data.userid=userid;
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	                product=json.data.product;
	                $("#txt_num").val(product.Num);
			        $("#txt_name").val(product.Name);
			        $("#txt_categoryid").val(product.CategoryID);
			        $("#txt_costprice").val(product.CostPrice);
			        $("#txt_price").val(product.Price);
			        $("#txt_bak").val(product.Bak); 
			        $("#photopanel").html(product.Img==""?"":"<img src='"+ (domain + product.Img)+"' width='50' height='50'/>"); 
	                Init_ProductTag(product);
	                Init_Category(product.CategoryID);
	                old_img=product.Img;
	            } else {
					plus.nativeUI.toast(json.msg);
	            }
	    });
    }else{
    	old_img=""; //必须加上，否则当修改产品后，old_img会残留旧值
		Init_ProductTag(); //初始化自定义Tag
		Init_Category();
	}
    
    
    get("addphoto").addEventListener('tap', function(event) {
				//get("share_context").blur();
						var btnArray = [{
							title: "拍照"
						}, {
							title: "从相册选择"
						}];
						plus.nativeUI.actionSheet({
							title: "选择照片",
							cancel: "取消",
							buttons: btnArray
						}, function(e) {
							var index = e.index;
							switch (index) {
								case 0:
									break;
								case 1:
									var cmr = plus.camera.getCamera();
									cmr.captureImage(function(path) {
										ResizeImg3("file://" + plus.io.convertLocalFileSystemURL(path));
									}, function(err) {});
									break;
								case 2:
									plus.gallery.pick(function(e) {
										for(var i in e.files){
									    	ResizeImg3(e.files[i]);
								    	}
									}, function(err) {}, {filter:"image",multiple:true});
									break;
							}
						});
					}, false);
};

function ResizeImg3(url){
	var image = new Image();
	image.src=url;
	var orientation=null;
	var rotate=0;
	image.onload=function(){ //图片加载完成
    //获取原始照片方向信息
    EXIF.getData(image,function () {
    	var height=1000*image.height/image.width;
        orientation = EXIF.getTag(this, "Orientation");
        if(orientation==1){//0°
            rotate=0;
            height=1000*image.height/image.width;
        }else if(orientation==6){//顺时针90°
            rotate=90;
            height=1000*image.width/image.height;
        }else if(orientation==8){//逆时针90°/顺时针270°
            rotate=270;
            height=1000*image.width/image.height;
        }else if(orientation==3){//180°
            rotate=180;
            height=1000*image.height/image.width;
        }
		var img=url.substring(url.lastIndexOf("/")+1, url.length).split(".")[0];
		plus.zip.compressImage(
					    {
					      src: url,
					      dst: '_doc/'+img+'_o.jpg',
					      overwrite: true,
					      width: '1000px', //这里指定了宽度，同样可以修改
					      height: parseInt(height)+'px',
					      format: 'jpg',
					      quality: 50  //图片质量不再修改，以免失真 
					    },
					    function(e) {
					      
					      $("#photopanel").html("<img src='" + e.target +"' width='50' height='50' onclick='remove_self(this)'/>");
					    },
					    function(err) {
					      plus.nativeUI.alert('未知错误！',function() {
					        mui.back();
					      });
					    }
		);
		});
    };
};

function Init_Category(categoryid){
	var data = {};
		data.act = "Find_AllCategory";
		data.source=source;
		data.userid=userid;
		data.comid=comid;
		data.sign=GetSign(data.act);
		mui.getJSON(crm_domain, data, function (json) {
	            if (json.state) {
	            	var str="";
	            	var selected="";
	            	$.each(json.data.category, function(i,info) {
	            		if(info.big.ID==categoryid)
	            		{
	            			selected="selected='selected'";
	            		}else
	            		{
	            			selected="";
	            		}
	            		str+='<option value="'+info.big.ID+'" '+selected+'>'+info.big.Name+'</option>';
	            		$.each(info.small, function(k,small) {
	            			if(small.ID==categoryid)
		            		{
		            			selected="selected='selected'";
		            		}else
		            		{
		            			selected="";
		            		}
	            			str+='<option value="'+small.ID+'" '+selected+'>'+small.Name+'</option>';
	            		});
	            	});
	            	$("#txt_categoryid").html(str);
	            }
	    });
};

function Init_ProductTag(customer)
{
	var buffer = new StringBuffer();
	
	var data = {};
	data.act = "Product_Tag";
	data.userid=userid;
	data.comid=comid;
	data.sign=GetSign(data.act);
	mui.getJSON(crm_domain, data, function(json) {
		$.each(json.data.taglist,function(i,info){
			if (info.Type == 1)
            {
			buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">'+info.Name+'</div>');
			if(info.IsRequired){
				buffer.append('<div class="require">*</div>');
			}
			buffer.append('</div><div class="ctext">');
			buffer.append('<select name="" class="select_new selftag" val="'+info.ColumnNum+'">');
                buffer.append('<option value="">选择'+info.Name+'</option>');
                $.each(info.TagDetail,function(k,detail)
                {
                	var isselect="";
                	if(customer){
                    if (info.ColumnNum == 1) { if (customer.Column1 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 2) { if (customer.Column2 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 3) { if (customer.Column3 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 4) { if (customer.Column4 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 5) { if (customer.Column5 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 6) { if (customer.Column6 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 7) { if (customer.Column7 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 8) { if (customer.Column8 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 9) { if (customer.Column9 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                    if (info.ColumnNum == 10) { if (customer.Column10 == detail.Name) { isselect = "selected='selected'"; } else { isselect = ""; } }
                   }
                   buffer.append('<option value="'+detail.Name+'" '+isselect +'>'+detail.Name+'</option>');
                });
                buffer.append('</select>');
			buffer.append('</div><div class="carrow"><img src="img/arrow.png"/></div></div>');
			}else{
			  var selftext = "";
			  if(customer){
              if (info.ColumnNum == 1) { selftext = customer.Column1; }
              if (info.ColumnNum == 2) { selftext = customer.Column2; }
              if (info.ColumnNum == 3) { selftext = customer.Column3; }
              if (info.ColumnNum == 4) { selftext = customer.Column4; }
              if (info.ColumnNum == 5) { selftext = customer.Column5; }
              if (info.ColumnNum == 6) { selftext = customer.Column6; }
              if (info.ColumnNum == 7) { selftext = customer.Column7; }
              if (info.ColumnNum == 8) { selftext = customer.Column8; }
              if (info.ColumnNum == 9) { selftext = customer.Column9; }
              if (info.ColumnNum == 10) { selftext = customer.Column10; }
              }
              buffer.append('<div class="crmsheet border-bottom"><div class="ctitle"><div class="cname">'+info.Name+'</div>');
              if(info.IsRequired){
              buffer.append('<div class="require">*</div>');
              }
              buffer.append('</div><div class="ctext"><input id="txt_name" type="text" class="selftag" placeholder="填写'+info.Name+'" value="'+selftext+'" val="'+info.ColumnNum+'"/></div></div>');
			}
		});
		$("#selfcontent").html(buffer.toString());
		
		buffer = new StringBuffer();
		$.each(json.data.unit,function(i,info){
			buffer.append('<option value="'+info.Name +'">'+info.Name+'</option>');
		});
		$("#txt_unit").html(buffer.toString());
		if(customer){
			$("#txt_unit").val(customer.Unit);
		}

	});
};


function Save_Product() {
        var data = {};
        var txt_num = $("#txt_num");
        var txt_name = $("#txt_name");
        if(txt_num.val().Trim()=="")
        {
        	plus.nativeUI.toast("请输入产品编号");
        	return false;
        }
        if(txt_name.val().Trim()=="")
        {
        	plus.nativeUI.toast("请输入产品名称");
        	return false;
        }
		var error = false;
        $("#selfcontent .require").parent().parent().find(".selftag").each(function () {
            var tagname = this.tagName.toLowerCase();
            if ($(this).val().Trim()=="") {
            	
                if (tagname == "input") {
                    plus.nativeUI.toast($(this).attr("placeholder"));
                } else {
                    plus.nativeUI.toast("请" + $(this).find("option:first").html());
                }
                error = true;
                return false;
            }
        });
        if (error) {
            return;
        }
		upload3(function(imgs){
        data.act = "Save_Product";
        data.id = $("#selfcontent").attr("val");
        data.userid=userid;
		data.comid=comid;
		data.num = $("#txt_num").val();
        data.name = $("#txt_name").val();
        data.categoryid = $("#txt_categoryid").val();
        data.categoryname = $("#txt_categoryid").find("option:selected").text();
        data.costprice = $("#txt_costprice").val();
        data.price = $("#txt_price").val();
        data.unit = $("#txt_unit").val();
        if(imgs!="")
		{
		    data.img=eval(imgs).join(",");
		}else
		{
		    data.img=old_img;
		}
		if (old_img == data.img) {
            data.imgchange = false;
        }
        else {
            data.imgchange = true;
        }
        data.old_img = old_img; //如果修改了图片，把旧照片传给服务器，删除掉
        data.bak = $("#txt_bak").val();
        data.source = source; 
        data.version = version;
        var selftag = new Array();
        $(".selftag").each(function () {
            selftag.push($(this).attr("val") + "*" + $(this).val());
        });
        data.selftag = selftag + "";
        data.sign=GetSign(data.act);
        mui.getJSON(crm_domain, data, function(json) {
            if (json.state) {
                CloseWindow();
                plus.nativeUI.toast(json.msg);
                if(data.id==0)
                {
                	Clear_Form();
                	Product_Search();
                }else{
                	Init_ProductDetail();
                	obj.find(".customername").html(data.name);
                	obj.find(".state").html("成本价："+data.costprice.toFixed(2));
                }
            } else {
				plus.nativeUI.toast(json.msg); 
            }
        });
    });
};


function upload3(fun){
      		if($("#photopanel img").length>0 && $("#photopanel img").attr("src")!= (domain + old_img))
      		{
				var wt=plus.nativeUI.showWaiting("正在上传图片...");
				var task=plus.uploader.createUpload(upload_domain,
					{method:"POST"},
					function(t,status){ //上传完成
						if(status==200){
							wt.close();
							fun(t.responseText);
						}else{
							wt.close();
						}
					}
				);
				var date = new Date();
				task.addData("userid",userid);
				task.addData("comid",comid);
				task.addData("handle","upload_product");
				task.addData("random",date.Format("hhmmss"));
				$("#photopanel img").each(function(){
					task.addFile(this.src,{key:this.src});
				});
				
				task.start();
			}
      		else{
      			fun("");
      		}
	};